package com.flw.eslab.web.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import org.springframework.stereotype.Component;

import com.flw.eslab.model.Resource;
import com.sina.sae.storage.StorageUtil;
import com.sina.sae.util.SaeUserInfo;

@Component("saeUtil")
public class SaeUtil {

	private String saeTempPath;
	private String fileSep;
	private SaeUserInfo saeUserInfo;

	public SaeUtil() {
		this.fileSep = System.getProperty("file.separator");
		this.saeTempPath = System.getProperty("java.io.tmpdir") + this.fileSep
				+ "SaeStoageDir" + this.fileSep;
	}

	  public Resource save2Sae(File file, String domainname, String fileName)
			throws IOException {

		Resource resource = new Resource(fileName,spellName(domainname, fileName),
				Long.toString(file.length()));
		
		InputStream is = new FileInputStream(file);
		// 因为sae的storage限定是10MB，file的尺寸不会超int的表示范围
		byte[] buf = new byte[(int) file.length()];

		is.read(buf);

		String str = URLEncoder.encode(fileName, "UTF-8");

		save4Storage(domainname, fileName, buf);

		is.close();

		return resource;

	}

	protected void save4Storage(String domain, String fileName, byte[] content) {
		String writeFileName = spellName(domain, fileName);
		StorageUtil.writeFile(writeFileName, content, -1);
	}

	protected String spellName(String domain, String fileName) {
		String writeFileName = this.saeTempPath + this.fileSep
				+ saeUserInfo.getAppName() + this.fileSep + domain
				+ this.fileSep + fileName;
		return writeFileName;
	}
}
